package com.easylinkin.linkappapi.childinspection.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.childinspection.entity.InspectionQrCodeEntity;
import com.easylinkin.linkappapi.childinspection.entity.InspectionRecordEntity;
import com.easylinkin.linkappapi.childinspection.entity.InspectionPointEntity;
import com.easylinkin.linkappapi.childinspection.mapper.InspectionPointMapper;
import com.easylinkin.linkappapi.childinspection.mapper.InspectionQrCodeMapper;
import com.easylinkin.linkappapi.childinspection.mapper.InspectionRecordMapper;
import com.easylinkin.linkappapi.childinspection.service.InspectionRecordService;
import com.easylinkin.linkappapi.childinspection.vo.BaseVo;
import com.easylinkin.linkappapi.childinspection.vo.InspectionRecordVo;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.lobar.entity.LaborCompany;
import com.easylinkin.linkappapi.lobar.mapper.LaborCompanyMapper;
import com.easylinkin.linkappapi.safe.dto.HiddenDangerDTO;
import com.easylinkin.linkappapi.safe.entity.HiddenDanger;
import com.easylinkin.linkappapi.safe.service.HiddenDangerService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import com.easylinkin.linkappapi.security.mapper.LinkappUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author linWenLe
 * @Date: 2024/4/11
 * @Description:
 */
@Slf4j
@Service("inspectionRecordService")
public class InspectionRecordServiceImpl extends ServiceImpl<InspectionRecordMapper, InspectionRecordEntity> implements InspectionRecordService {

    @Resource
    LinkappUserContextProducer linkappUserContextProducer;

    @Resource
    private InspectionRecordMapper inspectionRecordMapper;

    @Resource
    private InspectionPointMapper inspectionPointMapper;

    @Resource
    private LinkappUserMapper linkappUserMapper;

    @Resource
    private HiddenDangerService hiddenDangerService;

    @Resource
    private CommonService commonService;

    @Resource
    private InspectionQrCodeMapper inspectionQrCodeMapper;

    @Resource
    private LaborCompanyMapper laborCompanyMapper;


    @Override
    public IPage<InspectionRecordEntity> getList(RequestModel<BaseVo> restPage) {
        Page page = restPage.getPage();
        return inspectionRecordMapper.selectPointRecordInfoList(page, restPage.getCustomQueryParams());
    }

    /**
     *
     * @param entityVo
     */
    @Override
    public String insert(InspectionRecordVo entityVo) {
        Assert.notNull(entityVo.getPointId(), "巡检点编号不能为空");
        InspectionPointEntity pointEntity = inspectionPointMapper.selectById(entityVo.getPointId());
        LinkappUser current = linkappUserContextProducer.getNotNullCurrent();
        InspectionRecordEntity entity = new InspectionRecordEntity();
        BeanUtils.copyProperties(entityVo,entity);
        entity.setCreator(current.getCreator());
        commonService.setCreateAndModifyInfo(entity);
        entity.setUserId(entity.getCreator());
        entity.setType(checkUserStatus(pointEntity.getTenantId()) ? 1 : 0);
        String hiddenDangerId = "";
        if (entity.getStatus() == 1) {//正常
            if (StringUtils.isNotEmpty(entityVo.getHiddenDangerId())){//之前存在隐患  ***是/是***
                HiddenDanger hiddenDanger = entityVo.getHiddenDanger();
                if (hiddenDanger == null){//关闭隐患
                    hiddenDanger = hiddenDangerService.getOneById(entityVo.getHiddenDangerId());
                    hiddenDanger.setIsSceneRectify(1);
                    entity.setStatus(3);//设置为已整改
                }else {
                    //或者不关闭，直接修改隐患
                    if (hiddenDanger.getIsSceneRectify() == 1){
                        entity.setStatus(3);//如果为关闭,设置为已整改
                    }
                }
                hiddenDangerService.updateOneNew(hiddenDanger);
                hiddenDangerId = hiddenDanger.getId();
            }else {//之前不存在隐患，则新增隐患                                         ***是/否***
                HiddenDanger hiddenDanger = entityVo.getHiddenDanger();
                if (hiddenDanger != null){
                    HiddenDangerDTO hiddenDangerDTO = hiddenDangerService.saveOne(hiddenDanger);
                    entity.setHiddenDangerId(hiddenDangerDTO.getId());
                    hiddenDangerId = hiddenDangerDTO.getId();
                }
            }
        }else {//异常
            if (StringUtils.isNotEmpty(entityVo.getHiddenDangerId())){//之前存在隐患  ***否/是***
                HiddenDanger hiddenDanger = entityVo.getHiddenDanger();
                if (hiddenDanger.getId() == null) { //覆盖关闭，然后新增（重填）
                    HiddenDanger danger = hiddenDangerService.getOneById(entityVo.getHiddenDangerId());
                    danger.setIsSceneRectify(1);
                    //关闭原有隐患
                    hiddenDangerService.updateOneNew(danger);
                    //新增隐患
                    if (hiddenDanger.getIsSceneRectify() == 1){
                        entity.setStatus(3);//设置为已整改
                    }
                    HiddenDangerDTO hiddenDangerDTO = hiddenDangerService.saveOne(hiddenDanger);
                    entity.setHiddenDangerId(hiddenDangerDTO.getId());
                    hiddenDangerId = hiddenDangerDTO.getId();
                }else { //修改
                    if (hiddenDanger.getIsSceneRectify() == 1){
                        entity.setStatus(3);//设置为已整改
                    }
                    hiddenDangerService.updateOneNew(hiddenDanger);
                    hiddenDangerId = hiddenDanger.getId();
                }
            }else {//之前不存在隐患，则新增隐患                                         ***否/否***
                HiddenDanger hiddenDanger = entityVo.getHiddenDanger();
                Assert.notNull(hiddenDanger, "新增隐患不能为空");
                if (hiddenDanger.getIsSceneRectify() == 1){
                    entity.setStatus(3);//设置为已整改
                }
                HiddenDangerDTO hiddenDangerDTO = hiddenDangerService.saveOne(entityVo.getHiddenDanger());
                entity.setHiddenDangerId(hiddenDangerDTO.getId());
                hiddenDangerId = hiddenDangerDTO.getId();
            }
        }
        inspectionRecordMapper.deleteRecordById(entity.getPointId());
        //新增巡检记录
        inspectionRecordMapper.insert(entity);
        //修改任务关联表
        inspectionRecordMapper.updateTaskAndPointStatus(entity.getPointId(), entity.getStatus());
        return hiddenDangerId;
    }

    public Boolean checkUserStatus(String tenantId){
        LinkappUser current = linkappUserContextProducer.getNotNullCurrent();
        QueryWrapper<LinkappUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("tenant_id", tenantId).eq("username", current.getUsername());
        List<LinkappUser> linkappUsers = linkappUserMapper.selectList(userQueryWrapper);
        //true 巡检员, false 非巡检员
        return linkappUsers.size() > 0;
    }

    @Override
    public Map<String, Object> getPointAndUserInfo(String pointId) {
        QueryWrapper<InspectionPointEntity> wrapper = new QueryWrapper<>();
        InspectionPointEntity pointEntity = inspectionPointMapper.selectOne(wrapper.eq("id", pointId).eq("inspection_point_status", 1));
        if (pointEntity == null){
            InspectionQrCodeEntity codeEntity = inspectionQrCodeMapper.selectById(pointId);
            Assert.notNull(codeEntity, "巡检点不存在或者未开启");
            Assert.isTrue(codeEntity.getInspectionPointId() != null, "二维码未关联巡检点");
            pointId = codeEntity.getInspectionPointId();
            QueryWrapper<InspectionPointEntity> wrapperNew = new QueryWrapper<>();
            pointEntity = inspectionPointMapper.selectOne(wrapperNew.eq("id", pointId).eq("inspection_point_status", 1));
        }
        int count = inspectionPointMapper.selectCurrentTaskByPointId(pointId);
        Assert.isTrue(count > 0, "当前巡检点未创建当日任务");
        Boolean userStatus = checkUserStatus(pointEntity.getTenantId());
        Map<String, Object> map = new HashMap<>();
        map.put("id", pointEntity.getId());
        map.put("name", pointEntity.getInspectionPointName());
        map.put("code", pointEntity.getInspectionPointCode());
        map.put("userStatus", userStatus);
        return map;
    }

    @Override
    public InspectionRecordEntity findRecord(String pointId) {
        Assert.notNull(pointId, "巡检点编号不能为空");
        return inspectionRecordMapper.selectOneById(pointId);
    }

    @Override
    public Map<String, Object> findRecordAndDanger(String pointId) {
        Assert.notNull(pointId, "巡检点编号不能为空");
        InspectionRecordEntity record = inspectionRecordMapper.selectOneById(pointId);
        Map<String, Object> map = new HashMap<>();
        map.put("record", record);
        map.put("hiddenDanger", null);
        if (record != null && record.getHiddenDangerId() != null) {
            HiddenDanger hiddenDanger = hiddenDangerService.getById(record.getHiddenDangerId());
            LaborCompany laborCompany = laborCompanyMapper.selectById(hiddenDanger.getLinkUnitId());
            record.setUserDept(laborCompany.getName());
            int rectify = hiddenDanger.getIsSceneRectify() == null ? 1 : hiddenDanger.getIsSceneRectify();
            if (rectify != 1){
                map.put("hiddenDanger", hiddenDanger);
            }
        }
        return map;
    }

    @Override
    public Map<String, Object> getTaskCount(String taskId) {
        //巡检点数量
        List<InspectionPointEntity> point = inspectionPointMapper.selectPointList(taskId);
        //巡检记录数量
        List<InspectionRecordEntity> list = inspectionRecordMapper.getTaskCount(taskId);
        Map<String, Object> map = new HashMap<>();
        map.put("count", list.size() + "/" + point.size());
        return map;
    }

    @Override
    public HiddenDangerDTO selectOne(String id) {
        HiddenDangerDTO hiddenDangerDTO = hiddenDangerService.getOneById(id);
        Long rectifyUid = hiddenDangerDTO.getRectifyUid();
        if (rectifyUid != null){
            LinkappUser user = new LinkappUser();
            user.setId(rectifyUid);
            List<LinkappUser> rectifyUser = linkappUserMapper.selectUsers(user);
            if (rectifyUser.size() > 0){
                hiddenDangerDTO.setRectifyName(rectifyUser.get(0).getNickname());
            }
        }
        return hiddenDangerDTO;
    }
}
